package rs.parser;

import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/* Classe responsabile del parsing di un JSON relativo agli artisti simili ad un artista */
public class SimilarArtistParser {

	public List<String> parse(String response) {
		List<String> artists = new ArrayList<String>();
		if (!response.substring(2,7).equals("error")) {
			try {					
				JSONObject json = (JSONObject) new JSONParser().parse(response);
				JSONObject similarartists = (JSONObject) json.get("similarartists");

				Object artist_array = similarartists.get("artist");	
				if (artist_array == null) {
					return artists;
				}
				else if (artist_array instanceof JSONObject) {
					this.addArtist(artists, artist_array);
				}
				else {
					for (Object obj : (JSONArray)artist_array) {
						this.addArtist(artists, obj);
					}
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return artists;
	}

	private void addArtist(List<String> artists, Object obj) {
		try {
			JSONObject json_obj = (JSONObject) obj;
			String artist = (String) json_obj.get("name");		
			artists.add(artist);
		}
		catch (ClassCastException cce) {}
	}

}
